import { useMemo, useEffect, useState } from "react";
import FormRender from '@/components/FormRender';
import TableRender from '@/components/TableRender';
import { useLocation, useNavigate } from "react-router-dom";
import { getInventorytransactionRecordslist, getWarehouseList, getRealColumns, saveColumns } from "./service";
import ActionExportExcelModal from "./component/ActionExportExcelModal"; // 导出弹窗
import { useResize } from '@/views/hooks/useResize';
import { getFormItem, getColumns, getDefaultColumns } from './config.jsx';
import moment from 'moment';

//表格设置列code
const tableSetCode = 'ColsSettingStoreAccessRecords3213';

//快捷查询列
const quickSearchCode = 'quickSearch-AccessRecords3213';

const AccessRecords = () => {

	const [visible, setVisible] = useState();

	const location = useLocation();

	const navigate = useNavigate();

	const [warehouseList, setWarehouseList] = useState([]);

	const [data, setData] = useState([]);

	const [query, setQuery] = useState({});

	const [realColumns, setRealColumns] = useState([]);

	const [resetKey, setResetKey] = useState();

	//监听变更
	const { el: headerEl, height: headerHeight, onResize } = useResize();

	//分页数据
	const [pages, setPages] = useState({
		current: 1,
		total: 0,
		pageSize: 500,
		pageSizeOptions: [50, 100, 500, 1000, 5000],
	});

	//默认列
	const defaultColumns = useMemo(() => {
		return getDefaultColumns();
	}, [])

	//真实渲染列
	const columns = useMemo(() => {
		return getColumns(realColumns);
	}, [realColumns])

	useEffect(() => {
		getWarehouseFunc();
		queryRealColumns();
	}, []);

	useEffect(() => {
		getTableList();
	}, [query, pages.current, pages.pageSize])

	useEffect(() => {
		if ((location.state?.goodsCode || location.state?.warehouseId) && location.pathname == '/views/stock/AccessRecords') {
			setQuery({
				...query,
				warehouseId: location.state?.warehouseId,
				skuCode: location.state?.goodsCode
			})
			setResetKey(Date.now());
      navigate('/views/stock/AccessRecords', { state: {} });
		}
	}, [location.state?.goodsCode, location.state?.warehouseId]);


	//获取真实realcoulmns
	const queryRealColumns = async () => {
		const { success, data } = await getRealColumns({
			code: tableSetCode
		})
		if (success) {
			if (data.param) {
				setRealColumns(JSON.parse(data.param));
			} else {
				setRealColumns(defaultColumns);
			}
		}
	}

	//保存当前展示列
	const updateColumns = async (val, callback) => {
		const { success } = await saveColumns({
			code: tableSetCode,
			param: JSON.stringify(val)
		})
		if(success) {
			setRealColumns(val);
		}
		callback(success);
	}

	//获取任务列表
	const getTableList = async () => {
		const params = {
			...query,
			pageSize: pages.pageSize,
			pageNum: pages.current,
		};
		if (params.time) {
			params.createTimeStart = moment(params.time[0]).format('YYYY-MM-DD HH:mm:ss');
			params.createTimeEnd = moment(params.time[1]).format('YYYY-MM-DD HH:mm:ss');
		}
		params.time = undefined;
		START_LOADING();
		const { success, data } = await getInventorytransactionRecordslist(params);
		END_LOADING();
		if (success) {
			const { records = [], total } = data;
			setData(records);
			setPages({
				...pages,
				total
			})
		}
	};

	//点击仓库
	const clickWareHouse = (val) => {
		setQuery({
			warehouseId: val
		})
		setPages({
			...pages,
			current: 1
		})
	}

	//获取仓库列表
	const getWarehouseFunc = async () => {
		const { data = [], success } = await getWarehouseList();
		if (success) {
			if (data.length > 0) {
				const arr = data.map(v => {
					return {
						value: v.id,
						label: v.warehouseName
					}
				})
				setWarehouseList(arr);
			}
		}
	};

	//表单数据
	const formArr = useMemo(() => {
		return getFormItem({
			warehouseId: warehouseList
		}, clickWareHouse)
	}, [warehouseList])


	//操作按钮
	const btnArr = [
		{ elType: 'button', text: '表格导出', onClick: () => setVisible('ProgressModal') }
	]

	//表单渲染组件
	const FormRenderProps = {
		query,
		formArr,
		showExpand: true,
		showQuickSearch: true,
		quickSearchCode,
		resetKey,
		showKeys: ['businessType', 'warehouseType', 'skuName', 'skuCode', 'spuCode'],
		formConfig: {
			name: 'access-record-form',
			style: { marginBottom: '16px' }
		},
		clickSearch(val) {
			setPages({
				...pages,
				current: 1
			});
			setQuery(val);
		},
		clickReset() {
			setPages({
				...pages,
				current: 1
			});
			setQuery({});
		},
		clickExpand() {
			onResize();
		}
	}

	//表格组件
	const TableRenderProps = {
		data,
		columns,
		rowKey: 'id',
		style: {
			height: `calc(100vh - ${headerHeight + 208}px)`
		},
		operaConfig: {
			showOpera: true,
			operaLeftArr: btnArr,
			showTableSet: true,
			defaultColumns,
			realColumns,
			updateColumns(val, callback) {
				updateColumns(val, callback)
			}
		},
		pageConfig: {
			pages,
			handlePageSize(page, size) {
				setPages({
					...pages,
					current: page,
					pageSize: size
				});
			}
		}
	}

	const exportProps = {
		createTaskData: {
			businessParam: JSON.stringify({
				...query,
				createTimeStart: query.time ? moment(query.time[0]).format('YYYY-MM-DD HH:mm:ss') : undefined,
				createTimeEnd: query.time ? moment(query.time[1]).format('YYYY-MM-DD HH:mm:ss') : undefined,
				time: undefined,
				current: pages.current, // 当前页
				size: pages.pageSize, // 每页的数量
				businessKey: 3
			}),
			taskType: 4004
		},
		onCancel() {
			setVisible(null);
		}
	}


	return (
		<>
			<div ref={headerEl}>
				<FormRender {...FormRenderProps} />
			</div>
			<div className="global-page-wrap">
				<TableRender {...TableRenderProps} />
			</div>
			{visible == "ProgressModal" && <ActionExportExcelModal {...exportProps} />}
		</>
	);
};

export default AccessRecords;
